<?php

namespace app\controller;

use app\BaseController;

class Log extends BaseController
{
    /**
     * 获取登录日志
     */
    public function getLoginLog()
    {
        $uid = $this->getUid();
        if (empty($uid)) return pr(300, API_NEED_LOGIN);
        $page = $this->request->post('page', 1, 'int');
        $limit = $this->request->post('limit', 10, 'int');
        $list = $this->M("log_login")
            ->alias('ll')
            ->join('user u', 'll.uid = u.id')
            ->field('ll.*, u.nickname')
            ->page($page, $limit)
            ->order('ll.time','desc')
            ->select();
        $count = $this->M("log_login")->count();
        $list['_extra'] = ['sum' => $count];
        return pr(200, API_SUCCESS, $list);
    }
    /**
     * 获取管理员操作日志
     */
    public function getAdminLog()
    {
        $uid = $this->getUid();
        if (empty($uid)) return pr(300, API_NEED_LOGIN);
        if (!$this->checkAuth()) return pr(300, API_NO_AUTH);
        $page = $this->request->post('page', 1, 'int');
        $limit = $this->request->post('limit', 10, 'int');
        $list = $this->M("log_admin")
            ->alias('la')
            ->join('user u', 'la.uid = u.id')
            ->field('la.*, u.nickname')
            ->page($page, $limit)
            ->order('la.time','desc')
            ->select();
        $count = $this->M("log_admin")->count();
        $list['_extra'] = ['sum' => $count];

        return pr(200, API_SUCCESS, $list);
    }

     /**
     * 是否为管理员
     */
    private function checkAuth($isDevelopers = false,$uid1 = null): bool
    {
        if (!empty($uid1)) $uid = $uid1;
        else $uid = $this->getUid();
        if (empty($uid)) return false;
        try {
            if(!empty($isDevelopers))$check = $this->M('user_role')->where('uid', '=', $uid)->where('role_id', '=', 2)->find();
            else $check = $this->M('user_role')->where('uid', '=', $uid)->where('role_id', '=', 1)->find();
            if (empty($check)) return false; else return true;
        } catch (DataNotFoundException|ModelNotFoundException|DbException $e) {
            return false;
        }
    }
}